//对axios二次封装
import axios from "axios";
import store from '@/store';
import { Message } from 'element-ui'
//引入进度条
import nprogress from 'nprogress';
//引入进度条样式
import 'nprogress/nprogress.css';

//1、 创建axios实例---requests
const requests = axios.create({
    //基础路径，requests发出的请求在端口号后面会跟改baseURl
    baseURL: '/api',
    //超时时间
    timeout: 5000,
})

//2、配置请求拦截器
requests.interceptors.request.use(config => {
    //config内主要是对请求头Header配置
    //比如添加token

    //1、先判断uuid_token是否为空
    if (store.state.detail.uuid_token) {
        //2、userTempId字段和后端统一
        config.headers['userTempId'] = store.state.detail.uuid_token
    }
    if (store.state.user.token) {
        //2、token字段和后端统一
        config.headers['token'] = store.state.user.token
    }
    const token = store.state.user.token
    if (token) {
        config.headers['Authorization'] = `Bearer ${token}`
    }
    //开启进度条
    nprogress.start();
    return config;
}, err => {
    return Promise.reject(err);
})

//3、配置响应拦截器
requests.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code !== 200) {
            Message({
                message: res.message || '服务器错误',
                type: 'error',
                duration: 3000
            })
            return Promise.reject(new Error(res.message || '服务器错误'))
        }
        //响应成功，关闭进度条
        nprogress.done()
        return res
    },
    error => {
        let message = '连接服务器失败'
        if (error.response) {
            switch (error.response.status) {
                case 401:
                    message = '未授权，请重新登录'
                    store.dispatch('user/logout')
                    break
                case 403:
                    message = '拒绝访问'
                    break
                case 404:
                    message = '请求错误,未找到该资源'
                    break
                case 500:
                    message = '服务器错误'
                    break
                default:
                    message = error.response.data.message || '服务器响应错误'
            }
        }
        Message({
            message,
            type: 'error',
            duration: 3000
        })
        return Promise.reject(error)
    }
)

//4、对外暴露
export default requests;